1 下载链接
https://docs.pytest.org/en/latest/getting-started.html
或者使用pip安装
命令如下:
pip install pytest
更新命令:pip install -U pytest
查看版本pytest —version
2 pytest使用
2.1 基本测试
创建test_func.py
内容如下:
def func(x):return x + 1
def test_answer(): assert func(3) == 5
然后执行
#pytest test_func.py
collected 1items
test_func.py F
===================================FAILURES ===================================
_________________________________test_answer __________________________________
> def test_answer(): assert func(3) == 5
E assert 4 == 5
E + where 4 = func(3)
test_func.py:3: AssertionError
=========================== 1 failedin 0.02 seconds ===========================
测试结束,该用例测试失败。
因为函数结果因为4,不等于5嘛。
2.2 运行多个测试
pytest会在当前目录中运行所有文件以及子文件夹,需要以test_*.py或*_test.py文件。遵循标准规则。
-q参数表示quiet
创建test_class.py内容如下:
class TestClass:
def test_one(self):
x = "this"
assert 'h' in x
def test_two(self):
x = "hello"
assert hasattr(x, 'check')
测试结果如下:
1failed, 1 passed in 0.02 seconds
2.3 请求一个临时文件
创建test_temp.py内如如下:
def test_needsfiles(tmpdir):
print (tmpdir)
assert 0
然后执行,会报错
在测试函数中列出了tmpdir。
2.4 查看内置的参数
# pytest --fixtures